package com.wn.config;


import com.wn.interceptor.JwtInterceptor;
import com.wn.model.vo.UrlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
//开启配置项自动读取填充到对象属性中，且填充后的对象自动加入IoC容器
@EnableConfigurationProperties(UrlProperties.class)
@Slf4j
public class BookMvcConfig implements WebMvcConfigurer {
    //图片的访问地址
    @Value("${portal.image-path}")
    private String imagePath;

    @Autowired
    private JwtInterceptor jwtInterceptor;
    @Autowired
    private UrlProperties urlProperties;
    /**
     * 拦截器的配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //白名单从文件中读取
        List<String> whiteNames = urlProperties.getWhiteNames();
        log.info("白名单: {}", whiteNames);
        //要排除白名单
        registry.addInterceptor(jwtInterceptor).addPathPatterns("/**").excludePathPatterns(whiteNames);
    }

    /**
     * 配置资源的访问地址
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations(imagePath);
    }

    @Value("${portal.allowed-origins}")
    private String[] allowOrigins;
    /**
     * 允许所有类型的请求来自 http://localhost:9000 服务器
     * 并且允许的请求类型包括GET、POST、PUT、DELETE、OPTIONS
     * 允许与凭据一起发送请求，不然不能使用Cookie，导致会话不能使用
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  //允许所有访问地址
                .allowedOrigins(allowOrigins) //允许哪些服务器地址
                .allowedMethods("*")   //允许的请求类型
                .allowedHeaders("*")   //允许所有的请求头
                .allowCredentials(true)  //允许与凭据一起发送请求，Cookie可以跨域
                .exposedHeaders("*");   //允许返回的头信息
    }
}